#-*- coding=utf-8 -*-
from PIL import Image
import glob
import os,shutil
from LogUtil import Log
import time
from ConfigUtil import ConfigIni
from source.util.CommonUtil import getProjectDir


class PixelCompareUtil:
    def __init__(self,match_pics_dir,ini):
        self.logger=Log()
        self.match_pics_dir=match_pics_dir  #比对结束，将比对图片的前后5帧放入到指定目录
        self.ini=ini
        pass

    def pixel_compare(self,begin_time,path,locations,expectaions,compare_type,match_count,offset,timeout=30):
        '''
        :param begin_time 按键后开始时间
        :param path: 截图存放目录+待查找文件格式
        :param location: 待比较区域
        :param expectaion: 待比较rgb期望值
        :compare_type 0 反向比较，1 正向比较
        :timeout 超时时间 单位是秒
        :return: 比对时间，匹配图片路径
        '''
        time.sleep(2)
        start_time=int(time.time())
        index = int(self.ini.get_ini("test", "index"))
        last=index
        print "current index="+str(index)
        while int(time.time())-start_time<timeout:
            try:
                #files=glob.glob(path)
                files=sorted(glob.glob(path), key=os.path.getctime)
                for i,file in enumerate(files[index:]):
                    print "current file count="+str(len(files))+",current index=" + str(last+i)+",filename="+str(file)
                    im=Image.open(file)
                    pixel=im.load()
                    if self.check(locations,expectaions,pixel,compare_type,10,match_count,offset):
                        self.logger.info('图片文件名 %s' % os.path.basename(file))
                        c_time=int(os.path.getctime(file)*1000)   #获取图片创建时间
                        cost_time=self.computer_time(begin_time, c_time)
                        self.copy_file(i,files)
                        if last+i>0:
                            self.ini.set_ini("test","index",(last+i))  #连续比较，保存断点位置
                        dst=os.path.dirname(self.match_pics_dir) + "/img/" + os.path.basename(file)  #将命中图片移动到 img 文件夹
                        shutil.copyfile(file, dst)
                        return cost_time,c_time,dst
                last=len(files)
                if len(files)==0:
                    continue
                if index==len(files)-1:
                    return -1,-1,None
                if index<=len(files)-1:
                    index = len(files)-1
            except Exception as e:
                self.logger.error(str(e))
                time.sleep(2)
        self.logger.info('未找到符合条件的图片')
        return -1,-1,None

    def check(self,locations,expecations,pixel,compare_type,delta,match_count,offset):
        '''
        :param locations:  待搜索前图片的坐标集合
        :param expecation: 期望的rgb值
        :param delta: rgb允许的误差
        :return: True表示当前rbg与期望值一致，False相反
        '''
        matches=0
        for i,location in enumerate(locations):
            # r1, g1, b1 = eval(expecations[i])
            # location=location
            result=self.check_rgb(location, expecations[i], pixel, compare_type, delta, offset)
            if result:
                matches = matches + 1
                if matches >= match_count:
                    return True
                pass
            else:
                pass
        return False

    def check_rgb(self,location,rbg,pixel,compare_type,delta,offset):
        r1, g1, b1 = eval(rbg)
        # location=location
        for i in range(-offset, offset + 1):
            for j in range(-offset, offset + 1):
                x = location[0] + i
                y = location[1] + j
                r2, g2, b2 = pixel[x, y]
                if compare_type == 1:
                    if r1 - delta <= r2 <= r1 + delta and g1 - delta <= g2 <= g1 + delta and b1 - delta <= b2 <= b1 + delta:
                        print "expect:(x="+str(x)+",y="+str(y)+"),r1=" + str(r1) + ",g1=" + str(g1) + ",b1=" + str(b1)
                        print "reality:(x="+str(x)+",y="+str(y)+"),r2=" + str(r2) + ",g2=" + str(g2) + ",b2=" + str(b2)
                        return True
                    else:
                        continue
                elif compare_type == 0:
                    if r1 - delta <= r2 <= r1 + delta and g1 - delta <= g2 <= g1 + delta and b1 - delta <= b2 <= b1 + delta:
                        continue
                    elif (r1 - delta < r2 or r2 > r1 + delta) or (g1 - delta > g2 or g2 > g1 + delta) or (b1 - delta > b2 or b2 > b1 + delta):
                        print "expect:(x="+str(x)+",y="+str(y)+"),r1=" + str(r1) + ",g1=" + str(g1) + ",b1=" + str(b1)
                        print "reality:(x="+str(x)+",y="+str(y)+"),r2=" + str(r2) + ",g2=" + str(g2) + ",b2=" + str(b2)
                        return True              
        return False

    def computer_time(self,begin_time,end_time):
        '''
        :param begin_time:  按键发送成功的时间
        :param end_file: 匹配的图片路径
        :return:
        '''
        # end_time = int(os.path.getctime(end_file)*1000)
        self.logger.info(end_time-begin_time)
        cost_time=end_time-begin_time
        if cost_time<0:
            cost_time=0
        return cost_time


    def copy_file(self,i,files,interval=5):
        '''
        #比对结束，将比对成功图片的前后5帧放入到指定目录
        :param i: 找到图片在files中的下标
        :param files: 所有图片的文件列表
        :return:
        '''
        start=i-interval
        end=i+interval
        if start<0:
            start=0
        if end >len(files):
            end=len(files)
        for srcfile in files[start:end]:
            shutil.copyfile(srcfile, self.match_pics_dir+"/"+os.path.basename(srcfile))  # 复制文件
            pass
        pass

    # def computer_time(self,start_file,end_file):
    #     self.logger.info(start_file)
    #     self.logger.info(end_file)
    #     start_time=int(os.path.basename(start_file).split("_")[0])
    #     end_time = int(os.path.basename(end_file).split("_")[0])
    #     self.logger.info(end_time-start_time)
    #     return (end_time-start_time)

if __name__ == '__main__':
    '''
    遥控按键操作时间===1551864742507
    截图开始时间为===1551864742513
    第一张图片生成时间==1551864743346
    '''
    # end_time = int(os.path.getctime("D:/Test/001weather_1552358671/120190312104432_0.jpg") * 1000)
    # print(end_time-1551864742507)
    #
    # end_time = int(os.path.getctime("D:/Test/fenlei_1551864742/120190306173223_1.jpg") * 1000)
    # print(end_time - 1551864742507)

    # im = Image.open('E:/python/project/TerminateAutoTest/TestCase/apple.JPG')
    # pixel = im.load()
    # print(type(pixel))

    for i in range(-10,10+1):
        print(i)
    pass